import router from "@/router";
// 引入进度条
import nprogress from "nprogress";
import "nprogress/nprogress.css";
// 拿取token
import store from "@/store";

// 设置页面白名单
const whiteLsit = ["/login", "/404"];

//前置守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start();
  if (store.getters.token) {
    // 存在token
    if (to.path === "/login") {
      // 是登录页就跳转到主页
      next("/"); //此时并没有执行后置守卫
      nprogress.done();
    } else {
      // 判断是否有用户信息
      if (!store.getters.userId) {
        await store.dispatch("user/getUserInfo");
      }
      next();
    }
  } else {
    // 没有token
    // 先判断是否在白名单中
    if (whiteLsit.includes(to.path)) {
      next();
    } else {
      next("/login");
      nprogress.done();
    }
  }
});

// 后置守卫
router.afterEach(() => {
  nprogress.done();
});
